import 'dart:async';
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

import '../../../const/AppConst.dart';
import '../../../db/DbDAOHelper.dart';
import '../../../routes/app_pages.dart';
import '../../../services/AudioService.dart';
import '../../../utils/tips.dart';
import 'package:dio/dio.dart' as dio;


class IndexTranslationController extends GetxController {

  var arrows_btn = false.obs;
  var translateFocusNode = FocusNode().obs;
  TextEditingController textEditingController = TextEditingController();

  AudioService audioService = Get.find<AudioService>();

  Timer? monitorTimer;
  var hasClipboardData = false.obs;
  var hasTextContent = false.obs;
  var drawBackBtnShow = false.obs;

  var drawBackContent = ''.obs;
  String? taskId;

  ScrollController scrollController = new ScrollController();

  @override
  void onInit() {
    super.onInit();
    textEditingController.text = audioService.indexPageFinalFromLanguage.value;
    if(textEditingController.text.trim() != '') {
      arrows_btn.value = true;
    }

    monitorClipData();
  }

  void monitorClipData()  {
    monitorTimer = Timer.periodic(Duration(milliseconds: 500), (v) async {
      final ClipboardData? data = await Clipboard.getData('text/plain');
      if (data != null && data.text?.trim() != '') {
        hasClipboardData.value = true;
      } else {
        hasClipboardData.value = false;
      }

      if (textEditingController.text.trim() != '') {
        hasTextContent.value = true;
      } else {
        hasTextContent.value = false;
      }

    });
  }

  @override
  void onReady() {
    super.onReady();
    translateFocusNode.value.requestFocus();

    /*Future.delayed(Duration(milliseconds: 500),() {
      scrollController.jumpTo(0);
    });*/
  }

  @override
  void onClose() {
    super.onClose();
    translateFocusNode.value.unfocus();
    monitorTimer?.cancel();
  }

  void onTextChange(v) {
    audioService.indexPageFinalFromLanguage.value = v;
    audioService.indexPageFinalToLanguage.value = '';

    if (v != '') {
       arrows_btn.value = true;
    } else {
       arrows_btn.value = false;
    }

  }

  void cleanContent() {
    drawBackContent.value = textEditingController.text;
    textEditingController.text = '';
    audioService.indexPageFinalFromLanguage.value = '';
    audioService.indexPageFinalToLanguage.value = '';
    drawBackBtnShow.value = true;
    arrows_btn.value = false;
    hasClipboardData.value = false;
  }

  void drawBack() {
    textEditingController.text = drawBackContent.value;
    audioService.indexPageFinalFromLanguage.value = drawBackContent.value;
    drawBackBtnShow.value = false;
    arrows_btn.value = true;
  }

  void pastFromOtherSource() async {
    try {
      final ClipboardData? data = await Clipboard.getData('text/plain');
      if (data != null && data.text?.trim() != '') {
        print('粘贴内容: ${data.text!}');
        textEditingController.text = data.text!;
        audioService.indexPageFinalFromLanguage.value = data.text!;
        arrows_btn.value = true;

        await Clipboard.setData(ClipboardData(text: ''));

      } else {
        print('剪贴板为空或包含非文本内容');
        arrows_btn.value = false;
      }
    } on PlatformException catch (e) {
      print('读取剪贴板失败: ${e.message}');
      arrows_btn.value = false;
    }
  }


  void chooseFromLanguages() async {
    final languageItem = await Get.toNamed(Routes.LANGUAGE_OPINION,parameters: {
    'code': audioService.fromLanguage
    });
    audioService.fromLanguage = languageItem['code'];
    audioService.fromLanFlagDisplay.value = languageItem['desc'];
  }

  void chooseToLanguages() async {
    final languageItem = await Get.toNamed(Routes.LANGUAGE_OPINION,parameters: {
    'code': audioService.toLanguage
    });
    audioService.toLanguage = languageItem['code'];
    audioService.toLanFlagDisplay.value = languageItem['desc'];
  }


  void translationText2Text() async {
    if (audioService.indexPageFinalFromLanguage.value == '') {
      return;
    }

    if (audioService.indexPageFinalFromLanguage.value.length > 500) {

      Tips.showToast('文本翻译最大支持500字以内');
      return;
    }

    Tips.showLoading();

    dio.Response resp = await dio.Dio(
    ).post(
      'https://xy-apis.newtranx.com/mt/v1/text',
      data: {
        "srcLang": audioService.fromLanguage,
        "tgtLang": audioService.toLanguage,
        "texts": [audioService.indexPageFinalFromLanguage.value]
      },
      options: dio.Options(
        responseType: dio.ResponseType.stream,
        headers: {
          'X-Api-Key': '264e03da4958e5ea405dd8f63b87da898757b821',
          'Content-Type': 'application/json'},
      ),

    );

    resp.data?.stream
        .cast<List<int>>()
        .transform(Utf8Decoder())
        .listen((event) {
      Map<String,dynamic> contentParams = json.decode(event);
      if (contentParams['code'] == 200) {
        audioService.indexPageFinalToLanguage.value = contentParams['data']['content'][0]['text'];
        taskId = contentParams['data']['taskId'];

        DbDAOHelper().saveTranslateHistory(audioService.fromLanguage,
            audioService.toLanguage, audioService.indexPageFinalFromLanguage.value, audioService.indexPageFinalToLanguage.value, taskId!,AppConst.TRANSLATOIN_TYPE_DIRECT,
            audioService.fromLanFlagDisplay.value,audioService.toLanFlagDisplay.value);

        Tips.dismissLoading();

        Get.toNamed(Routes.TRANSLATE_RESULT,parameters: {
          'content': textEditingController.text,
          /*'fromLanguage': controller.audioService.fromLanguage,
                               'fromLanguageDisplay': controller.audioService.fromLanFlagDisplay.value,
                               'toLanguage': controller.audioService.toLanguage,
                               'toLanguageDisplay': controller.audioService.toLanFlagDisplay.value*/
        });

      } else {
        audioService.indexPageFinalToLanguage.value = '翻译失败,请重新尝试.';
      }
    },
    );
  }

}
